package loan.calc.datasource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.autoconfigure.SqlSessionFactoryBeanCustomizer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfiguration {

    public static final String DATA_SOURCE_BEAN_NAME_SUFFIX = "DataSource";
    public static final String TRANSACTION_MANAGER_BEAN_NAME_SUFFIX = "TransactionManager";

    @Bean(name = DataSourceNames.MASTER + DATA_SOURCE_BEAN_NAME_SUFFIX,
            initMethod = "init", destroyMethod = "close")
    @ConfigurationProperties("spring.datasource.druid." + DataSourceNames.MASTER)
    public DataSource masterDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = DataSourceNames.MASTER + TRANSACTION_MANAGER_BEAN_NAME_SUFFIX)
    @Primary
    public TransactionManager masterDataSourceTransactionManager(@Qualifier(DataSourceNames.MASTER + DATA_SOURCE_BEAN_NAME_SUFFIX) DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = DataSourceNames.SLAVE + DATA_SOURCE_BEAN_NAME_SUFFIX,
            initMethod = "init", destroyMethod = "close")
    @ConfigurationProperties("spring.datasource.druid." + DataSourceNames.SLAVE)
    public DataSource slaveDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = DataSourceNames.SLAVE + TRANSACTION_MANAGER_BEAN_NAME_SUFFIX)
    public TransactionManager slaveDataSourceTransactionManager(@Qualifier(DataSourceNames.SLAVE + DATA_SOURCE_BEAN_NAME_SUFFIX) DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    @Primary
    public DynamicDataSource dynamicDatasource(DataSource masterDataSource,
                                               DataSource slaveDataSource) {
        Map<Object, Object> dataSourceMap = new HashMap<>(2);
        dataSourceMap.put(DataSourceNames.MASTER, masterDataSource);
        dataSourceMap.put(DataSourceNames.SLAVE, slaveDataSource);
        //设置动态数据源
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(dataSourceMap);
        dynamicDataSource.setDefaultTargetDataSource(masterDataSource);
        return dynamicDataSource;
    }

}
